package reduce.fz.com.reduce.util.oss;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.alibaba.sdk.android.oss.OSSService;
import com.alibaba.sdk.android.oss.OSSServiceProvider;
import com.alibaba.sdk.android.oss.callback.SaveCallback;
import com.alibaba.sdk.android.oss.model.AuthenticationType;
import com.alibaba.sdk.android.oss.model.OSSException;
import com.alibaba.sdk.android.oss.model.OSSFederationToken;
import com.alibaba.sdk.android.oss.model.StsTokenGetter;
import com.alibaba.sdk.android.oss.storage.OSSBucket;
import com.alibaba.sdk.android.oss.storage.OSSFile;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.bean.ICard;
import reduce.fz.com.reduce.bean.Pic;
import reduce.fz.com.reduce.bean.Video;
import reduce.fz.com.reduce.constant.ParamConst;
import reduce.fz.com.reduce.util.DateUtil;
import reduce.fz.com.reduce.util.ImageCompressUtil;
import reduce.fz.com.reduce.util.MD5;
import reduce.fz.com.reduce.util.base.FileCache;
import reduce.fz.com.reduce.util.base.ReduceApplication;
import reduce.fz.com.reduce.util.oss.model.FederationToken;
import reduce.fz.com.reduce.util.oss.model.FederationTokenGetter;

/**
 * Created by qingshengzheng on 15/11/9.
 */
public class VideoOss {
    private Context context;
    private static VideoOss oss = null;

    static {
    }

    public VideoOss(Context context) {
        this.context = context;
        setConfig();
        init();
        initSts();
        initBucket();
    }

    /**
     * 获取oss
     *
     * @return
     */
    public static VideoOss instance() {
        Context context = ReduceApplication.getInstance().getApplicationContext();
        if (oss == null)
            oss = new VideoOss(context);
        return oss;
    }

    /**
     * 文件上传
     *
     * @param response
     */
    private void uploadCard(final ICard card, final OssUploadResponse response, final List<ICard> successCards, final List<ICard> failedCards) {
        String lastprefix = "";
        String contentType = "";
        String newpath = "";
        final String localpath = card.getLocalPath();
        switch (card.getType()) {
            case ParamConst.CARD_TYPE_VIDEO:
                lastprefix = "mp4";
                contentType = "video/mp4";
                break;
            case ParamConst.CARD_TYPE_PIC:
                lastprefix = "png";
                contentType = "image/png";
                break;
            default:
                break;
        }
        if (ParamConst.CARD_TYPE_PIC == card.getType()) {
            newpath = FileCache.getCropDir(context) + MD5.md5(localpath) + "_" + new Random().nextInt(10000) + "." + lastprefix;
            final Map<String, Integer> params = ImageCompressUtil.compressByQuality(localpath, newpath);
        } else {
            newpath = localpath;
        }
        String ossName = System.currentTimeMillis() + "_" + new Random().nextInt(1000) + "." + lastprefix;
        final OSSFile ossFile = ossService.getOssFile(mybucket, ossName);
        try {
            ossFile.setUploadFilePath(newpath, contentType); // 指明需要上传的文件的路径，和文件内容类型，如果文件不存在将抛出异常
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // ossFile.enableUploadCheckMd5sum(); // 开启上传md5校验
        final String url = ossFile.getResourceURL();
        ossFile.uploadInBackground(new SaveCallback() {
            @Override
            public void onSuccess(String objectKey) {
                card.setUrl(url);
                successCards.add(card);
            }

            @Override
            public void onProgress(String objectKey, int byteCount, int totalSize) {

            }

            @Override
            public void onFailure(String objectKey, OSSException ossException) {
                failedCards.add(card);
            }
        });
    }

    /**
     * 上传视频
     * @param video
     * @param response
     */
    public void uploadVideo(final Video video, final OssUploadResponse response) {
        final List<ICard> successCards = new ArrayList<ICard>();
        final List<ICard> failedCards = new ArrayList<ICard>();
        Pic pic = new Pic(video.getLocalThumPath());
        uploadCard(video, response, successCards, failedCards);
        uploadCard(pic, response, successCards, failedCards);
        new Handler() {
            public void handleMessage(Message msg) {
                if (successCards.size() + failedCards.size() >= 2) {
                    List<Pic> pics = new ArrayList<Pic>();
                    if (successCards.size() == 2) {
                        video.thumUrl=getThumUrl(successCards);
                        response.onSuccess(video);
                    } else
                        response.onFailed(video);
                } else {
                    sendEmptyMessageDelayed(0, 1000);
                }

            }
        }.sendEmptyMessage(0);
    }

    public String getThumUrl(List<ICard> cards) {
        if (cards == null || cards.size() == 0 || cards.isEmpty())
            return "";
        for (int i = 0; i < cards.size(); i++) {
            if (ParamConst.CARD_TYPE_PIC == cards.get(i).getType())
                return ((Pic) cards.get(i)).url;
        }
        return "";
    }


    public interface OssUploadResponse {
        public void onSuccess(Video video);

        public void onFailed(Video video);
    }

    public interface OssVideoResponse {
        public void onSuccess(Video video);

        public void onProgress(int complete, int total);

        public void onFailed(Video video);
    }


    public void initBucket() {
        mybucket = ossService.getOssBucket(bucketName);
    }

    private OSSBucket mybucket;
    //oss服务
    public static OSSService ossService;
    //请求token业务服务器地址
    public static String serverAddress;
    //oss节点
    public static String endPoint;
    //oss bucket名称
    public static String bucketName;

    /**
     * 初始化
     */
    private void setConfig() {
        try {
            serverAddress = context.getResources().getString(R.string.oss_server);
            bucketName = context.getResources().getString(R.string.oss_bucket);
            endPoint = context.getResources().getString(R.string.oss_endpoint);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() {
        try {
            ossService = OSSServiceProvider.getService();
            ossService.setApplicationContext(context);
            ossService.setGlobalDefaultHostId(endPoint);
            ossService.setAuthenticationType(AuthenticationType.FEDERATION_TOKEN);
        } catch (Exception e) {
            e.printStackTrace();
            ;
        }
    }

    /**
     * 配置STS生成机制
     */
    public void initSts() {
        ossService.setGlobalDefaultStsTokenGetter(new StsTokenGetter() {
            @Override
            public OSSFederationToken getFederationToken() {
                // 为指定的用户拿取服务其授权需求的FederationToken
                FederationToken token = FederationTokenGetter.getToken(serverAddress, "");
                return new OSSFederationToken(token.getAccessKeyId(), token.getAccessKeySecret(), token.getSecurityToken(), DateUtil.getTimeFromQz(token.getExpiration()));
            }
        });
    }

}
